package com.kamikaze.docidset.impl;

import java.io.IOException;
import java.io.Serializable;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;

public class NotDocIdSet extends DocIdSet implements Serializable
{
  
  private static final long serialVersionUID = 1L;
  
  private DocIdSet innerSet = null;
  private DocIdSetIterator it1 = null;
  private int max = -1;
  
  public NotDocIdSet(DocIdSet docSet, int maxVal)
  {
	innerSet = docSet;  
    max = maxVal;
  }
  
  
  
  class NotDocIdSetIterator extends DocIdSetIterator
  {
    int lastReturn = -1;
    
    NotDocIdSetIterator() 
    {
        initialize();
    }

    private void initialize() 
    {
    	it1 = innerSet.iterator();
    	
        try
        {
          it1.next();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
    }

    @Override
    public int doc()
    {
      return lastReturn;
    }

    @Override
    public int getCursor()
    {
      // TODO Auto-generated method stub
      return -1;
    }

    @Override
    public boolean next() throws IOException
    {
      lastReturn ++;
      
      if(lastReturn < max && lastReturn < it1.doc())
        return true;
      else 
      {
        while(lastReturn >= it1.doc() && lastReturn < max)
        {
         if(it1.doc() == lastReturn){	
	          if(!it1.next())
	          {
	           	  return false;
	          } 
         }
         else if(!it1.next())
        	 break;
          // Increment this only if we are in the range.
          if(lastReturn <= it1.doc())
            lastReturn ++;
        }
        if(lastReturn  < max )
        {
            return true;
        }
        else
          return false;
       }
    }

	@Override
	public boolean skipTo(int target) throws IOException
	{
		if(target>max)
			return false;
		
		if(it1.skipTo(target))
		{
			lastReturn = target;
			while(it1.doc() <= lastReturn)
			{	
				lastReturn ++;
				it1.next();
			}
			
			if(lastReturn <=max)
				return true;
			
			return false;
				
		}
		else if(target <= max)
		{
			lastReturn = target;
			return true;
		}
		
		else
			return false;
	}
  }

  @Override
  public DocIdSetIterator iterator()
  {
      return new NotDocIdSetIterator();
  }

}